//
// ========================================================================
// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others.
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License v. 2.0 which is available at
// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
// which is available at https://www.apache.org/licenses/LICENSE-2.0.
//
// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
// ========================================================================
//

package org.eclipse.jetty.websocket.core;

import java.net.Socket;
import java.util.concurrent.Exchanger;
import java.util.concurrent.TimeUnit;
import java.util.function.BiConsumer;

import org.eclipse.jetty.logging.StacklessLogging;
import org.eclipse.jetty.util.Callback;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;

import static org.eclipse.jetty.util.Callback.NOOP;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;

/**
 * Tests of a core server with a fake client
 */
public class WebSocketOpenTest extends WebSocketTester
{
    private WebSocketServer server;
    private NonDemandingAsyncFrameHandler serverHandler;
    private Socket client;

    @AfterEach
    public void after() throws Exception
    {
        if (server != null)
            server.stop();
    }

    public void setup(BiConsumer<CoreSession, Callback> onOpen) throws Exception
    {
        serverHandler = new NonDemandingAsyncFrameHandler(onOpen);
        server = new WebSocketServer(serverHandler);
        server.start();
        client = newClient(server.getLocalPort());
    }

    @Test
    public void testSendFrameInOnOpen() throws Exception
    {
        setup((s, c) ->
        {
            assertThat(s.toString(), containsString("CONNECTED"));
            s.sendFrame(new Frame(OpCode.TEXT, "Hello"), NOOP, false);
            c.succeeded();
            s.demand();
        });
        Frame.Parsed frame = receiveFrame(client.getInputStream());
        assertThat(frame.getPayloadAsUTF8(), is("Hello"));

        client.getOutputStream().write(RawFrameBuilder.buildClose(new CloseStatus(CloseStatus.NORMAL), true));
        assertTrue(serverHandler.closeLatch.await(5, TimeUnit.SECONDS));
        assertThat(serverHandler.closeStatus.getCode(), is(CloseStatus.NORMAL));

        frame = receiveFrame(client.getInputStream());
        assertThat(frame.getOpCode(), is(OpCode.CLOSE));
        assertThat(new CloseStatus(frame).getCode(), is(CloseStatus.NORMAL));
    }

    @Test
    public void testFailureInOnOpen() throws Exception
    {
        try (StacklessLogging ignored = new StacklessLogging(WebSocketCoreSession.class))
        {
            setup((s, c) ->
            {
                assertThat(s.toString(), containsString("CONNECTED"));
                c.failed(new Exception("Test Exception in onOpen"));
            });

            assertTrue(serverHandler.closeLatch.await(5, TimeUnit.SECONDS));
            assertThat(serverHandler.error, notNullValue());

            assertTrue(serverHandler.closeLatch.await(5, TimeUnit.SECONDS));
            assertThat(serverHandler.closeStatus.getCode(), is(CloseStatus.SERVER_ERROR));

            Frame.Parsed frame = receiveFrame(client.getInputStream());
            assertThat(frame.getOpCode(), is(OpCode.CLOSE));
            assertThat(new CloseStatus(frame).getCode(), is(CloseStatus.SERVER_ERROR));
        }
    }

    @Test
    public void testCloseInOnOpen() throws Exception
    {
        setup((s, c) ->
        {
            assertThat(s.toString(), containsString("CONNECTED"));
            s.close(CloseStatus.SHUTDOWN, "Test close in onOpen", c);
        });

        Frame.Parsed frame = receiveFrame(client.getInputStream());
        assertThat(frame.getOpCode(), is(OpCode.CLOSE));
        assertThat(new CloseStatus(frame).getCode(), is(CloseStatus.SHUTDOWN));

        client.getOutputStream().write(RawFrameBuilder.buildClose(new CloseStatus(CloseStatus.NORMAL), true));
        assertTrue(serverHandler.closeLatch.await(5, TimeUnit.SECONDS));
        assertThat(serverHandler.closeStatus.getCode(), is(CloseStatus.SHUTDOWN));
    }

    @Test
    public void testAsyncOnOpen() throws Exception
    {
        Exchanger<CoreSession> sx = new Exchanger<>();
        Exchanger<Callback> cx = new Exchanger<>();
        setup((s, c) ->
        {
            assertThat(s.toString(), containsString("CONNECTED"));
            try
            {
                sx.exchange(s);
                cx.exchange(c);
            }
            catch (InterruptedException e)
            {
                throw new RuntimeException(e);
            }
        });

        CoreSession coreSession = sx.exchange(null);
        Callback onOpenCallback = cx.exchange(null);
        Thread.sleep(100);

        // Can send while onOpen is active
        coreSession.sendFrame(new Frame(OpCode.TEXT, "Hello"), NOOP, false);
        Frame.Parsed frame = receiveFrame(client.getInputStream());
        assertThat(frame.getPayloadAsUTF8(), is("Hello"));

        // Succeeded moves to OPEN state.
        onOpenCallback.succeeded();
        assertThat(coreSession.toString(), containsString("OPEN"));

        // Demanding in onOpen will allow you to receive frames.
        client.getOutputStream().write(RawFrameBuilder.buildFrame(OpCode.TEXT, "message in onOpen", true));
        assertNull(serverHandler.receivedFrames.poll(1, TimeUnit.SECONDS));
        coreSession.demand();
        Frame rcvFrame = serverHandler.receivedFrames.poll(5, TimeUnit.SECONDS);
        assertNotNull(rcvFrame);
        assertThat(rcvFrame.getPayloadAsUTF8(), is("message in onOpen"));

        // Demand to receive the close frame.
        client.getOutputStream().write(RawFrameBuilder.buildClose(new CloseStatus(CloseStatus.NORMAL), true));
        assertFalse(serverHandler.closeLatch.await(1, TimeUnit.SECONDS));
        coreSession.demand();
        assertTrue(serverHandler.closeLatch.await(5, TimeUnit.SECONDS));

        // Closed handled normally
        assertTrue(serverHandler.closeLatch.await(5, TimeUnit.SECONDS));
        assertThat(serverHandler.closeStatus.getCode(), is(CloseStatus.NORMAL));
        frame = receiveFrame(client.getInputStream());
        assertThat(frame.getOpCode(), is(OpCode.CLOSE));
        assertThat(new CloseStatus(frame).getCode(), is(CloseStatus.NORMAL));
    }

    static class NonDemandingAsyncFrameHandler extends TestAsyncFrameHandler
    {
        private final BiConsumer<CoreSession, Callback> onOpen;

        NonDemandingAsyncFrameHandler(BiConsumer<CoreSession, Callback> onOpen)
        {
            this.onOpen = onOpen;
        }

        @Override
        public void onOpen(CoreSession coreSession, Callback callback)
        {
            if (LOG.isDebugEnabled())
                LOG.debug("[{}] onOpen {}", name, coreSession);
            this.coreSession = coreSession;
            onOpen.accept(coreSession, callback);
            openLatch.countDown();
        }

        @Override
        public void onFrame(Frame frame, Callback callback)
        {
            if (LOG.isDebugEnabled())
                LOG.debug("[{}] onFrame {}", name, frame);
            receivedFrames.offer(Frame.copy(frame));
            callback.succeeded();
        }
    }
}
